package com.example.bookshop.dao;

import com.example.bookshop.bean.AdminBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/*
    专门操作admin表
 */
@Component
public class AdminDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 登陆操作根据账号密码查询是否存在用户
     * @param account
     * @param pass
     * @return
     */
    public AdminBean selectByAccountAndPass(String account,String pass){
        String sql="SELECT admin_id,account,pass,nick_name FROM admin WHERE account=? AND pass=?";
        List<AdminBean> admins = new ArrayList<>();
        admins = jdbcTemplate.query(sql, new RowMapper<AdminBean>() {

            @Override
            public AdminBean mapRow(ResultSet rs, int rowNum) throws SQLException {
                AdminBean admin = new AdminBean();
                admin.setId(rs.getInt("admin_id"));
                admin.setAccount(rs.getString("account"));
                admin.setPassword(rs.getString("pass"));
                admin.setNickName(rs.getString("nick_name"));
                return admin;
            }
        },account,pass);
        return admins==null || admins.size()==0?null:admins.get(0);
    }

    public int updatePass(String account, String newPass) {
        String sql="UPDATE admin SET pass=? WHERE account=?";
        return jdbcTemplate.update(sql,newPass,account);
    }

    public int updateAccountAndNickName(String oldAccount,String newAccount,String nickName){
        String sql = "UPDATE admin SET account=?,nick_name=? WHERE account=?";
        return jdbcTemplate.update(sql,newAccount,nickName,oldAccount);
    }
}
